package com.chinatelecom.ifree.business.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SerializeUtil {
	private static final Logger logger = LoggerFactory.getLogger(SerializeUtil.class);

	/**
	 * 序列化
	 * 
	 * @param <T>
	 * @param t
	 * @return
	 */
	public static byte[] serialize(Object o) {
		ByteArrayOutputStream baos = null;
		ObjectOutputStream oos = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(o);
			oos.flush();
			return baos.toByteArray();
		} catch (Exception e) {
			logger.error("exception", e);
		} finally {
			try {
				if (null != baos)
					baos.close();
			} catch (Exception e) {
				logger.error("exception", e);
			}
			try {
				if (null != oos)
					oos.close();
			} catch (Exception e) {
				logger.error("exception", e);
			}
		}
		return null;
	}

	/**
	 * 反序列化
	 * 
	 * @param <T>
	 * @param t
	 * @param bytes
	 */
	public static Object deserialize(byte[] bytes) {
		ByteArrayInputStream bais = null;
		ObjectInputStream ois = null;
		try {
			bais = new ByteArrayInputStream(bytes);
			ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (Exception e) {
			logger.error("exception", e);
		} finally {
			try {
				if (null != bais)
					bais.close();
			} catch (Exception e) {
				logger.error("exception", e);
			}
			try {
				if (null != ois)
					ois.close();
			} catch (Exception e) {
				logger.error("exception", e);
			}
		}
		return null;
	}

	public static byte[] serializeObj(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			// 序列化
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			byte[] bytes = baos.toByteArray();
			return bytes;
		} catch (Exception e) {
			logger.error("serializeObj", e);
		}
		return null;
	}

	public static Object unserializeObj(byte[] bytes) {
		ByteArrayInputStream bais = null;
		try {
			// 反序列化
			bais = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (Exception e) {
		}
		return null;
	}
}
